package complexity;

import java.util.Iterator;

public class SymbolTable<K extends Comparable<K>,V>{
    public static void main(String[] args) {
        SymbolTable<Integer, String> table = new SymbolTable<Integer, String>();
        table.put(1,"b");
        table.put(5,"bcd");
        table.put(2,"b");
        table.put(4,"bc");
        table.put(4,"bcsd");
        System.out.println(table.get(4));
    }
    private Node head;
    private int N;
    public SymbolTable() {
        this.head = new Node(null,null,null);
        this.N = 0;
    }
    public void put(K k,V value){
        Node node = this.head;
        Node newNode = new Node(k, value, null);
        while (node.next!=null){
            Node oldNode = node;
            node= node.next;
            if (k.compareTo(node.key)==0){
                node.value=value;
                return;
            }
            if (k.compareTo(node.key)<0){
                oldNode.next=newNode;
                newNode.next=node;
                this.N++;
                return;
            }
        }
        node.next=newNode;
        this.N++;
    }
    public int size(){
        return this.N;
    }
    public V get(K key){
        Node node = this.head;
        while (node.next!=null){
            node=node.next;
            if (node.key.equals(key)){
                return node.value;
            }
        }
        System.out.println("没有这个key");
        return null;
    }
    public void insert(K key,V v){
        Node n =this.head;
        while (n.next!=null){
            n=n.next;
            if (n.key.equals(key)){
                n.value=v;
                return;
            }
        }
        Node newNode = new Node(key,v,null);
        Node oldNode = head.next;
        newNode.next=oldNode;
        head.next=newNode;
        this.N++;
    }
    public V delete(K key){
        Node node = this.head;
        while (node.next!=null){
            if (node.next.key.equals(key)){
                node.next=node.next.next;
                this.N--;
                return node.next.value;
            }
        }
//        while (node.next!=null){
//           Node oldNode = node;
//            node=node.next;
//            if (node.key.equals(key)){
//                oldNode.next=node.next;
//                this.N--;
//                return node.value;
//            }
//        }
        System.out.println("不存在这个key");
        return null;
    }


    private class Node{
        private K key;
        private V value;
        private Node next;

        @Override
        public String toString() {
            return "Node{" +
                    "key=" + key +
                    ", value=" + value +
                    ", next=" + next +
                    '}';
        }

        public Node(K key, V value, Node next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }
}
